package com.rzico.sbl.ui.manager

import android.widget.ImageView
import androidx.core.view.isGone
import androidx.recyclerview.widget.RecyclerView
import com.google.android.flexbox.AlignItems
import com.google.android.flexbox.FlexDirection
import com.google.android.flexbox.FlexWrap
import com.google.android.flexbox.FlexboxItemDecoration
import com.google.android.flexbox.FlexboxLayoutManager
import com.google.android.flexbox.JustifyContent
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lzg.extend.jackson.JsonUtil
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityPickupCategoryBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.PickCategory
import com.rzico.sbl.other.showMemoDialog
import com.rzico.sbl.viewmodel.PickupViewModel
import com.xinnuo.common.extend.condition
import com.xinnuo.common.extend.conditionFalse
import com.xinnuo.common.extend.get
import com.xinnuo.common.extend.getDrawableEx
import com.xinnuo.common.extend.oneClick
import com.xinnuo.common.extend.swap
import com.xinnuo.common.helper.LogcatHelper
import com.xinnuo.common_ui.base.BaseActivity
import com.xinnuo.common_ui.base.addItems
import com.xinnuo.slimadapter.SlimAdapter
import com.xinnuo.slimadapter.swipe.OnItemDragListener


class PickupCategoryActivity : BaseActivity(R.layout.activity_pickup_category) {

    private val mBinding by lazy {
        ActivityPickupCategoryBinding.bind(getRootView())
    }

    private lateinit var mAllAdapter: SlimAdapter
    private val mAllList = arrayListOf<PickCategory>()
    private val mCheckList = arrayListOf<PickCategory>()
    private var isModify = false

    override fun getViewModel() = get<PickupViewModel>()

    override fun initData() {
        initTitle(title = "分类管理")

        initLayout()

        getData()
    }

    private fun initLayout() {
        mBinding.apply {
            categorySelect.apply {
                isNestedScrollingEnabled = false

                layoutManager = FlexboxLayoutManager(
                    context,
                    FlexDirection.ROW,
                    FlexWrap.WRAP
                ).apply {
                    justifyContent = JustifyContent.FLEX_START
                    alignItems = AlignItems.FLEX_START
                }

                addItemDecoration(
                    FlexboxItemDecoration(getIContext())
                        .apply {
                            setDrawable(getDrawableEx(R.drawable.rect_flex_space))
                        }
                )

                mAdapter = SlimAdapter.creator()
                    .register<PickCategory>(R.layout.item_pickup_category) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_category_name, bean.name)
                            image(R.id.item_category_flag, R.mipmap.icon_other02)

                            clicked(R.id.item_category_flag) {
                                categoryUpdate(
                                    arrayOf(
                                        "id" to bean.id,
                                        "show" to "0"
                                    )
                                ) {
                                    mCheckList.removeAt(index)
                                    mAdapter.apply {
                                        notifyItemRemoved(index)
                                        notifyItemRangeChanged(index, mCheckList.size - index)
                                    }

                                    mAllList.first { it.id == bean.id }.show = false
                                    mAllAdapter.notifyDataSetChanged()

                                    isModify = true
                                }
                            }
                        }
                    }
                    .attachTo(this)
                    .setItemTouchHelper()
                    .setDragItem(true)
                    .setOnItemDragListener(object : OnItemDragListener {
                        override fun onItemDragEnd(viewHolder: RecyclerView.ViewHolder, pos: Int) {
                            viewHolder.itemView.scaleX = 1f
                            viewHolder.itemView.scaleY = 1f

                            getViewModel()
                                .delay(100) {
                                    mAdapter.notifyDataSetChanged()
                                    categorySort()
                                }
                        }

                        override fun onItemDragMoving(
                            source: RecyclerView.ViewHolder,
                            from: Int,
                            target: RecyclerView.ViewHolder,
                            to: Int
                        ) {
                            mCheckList.swap(from, to)
                        }

                        override fun onItemDragStart(
                            viewHolder: RecyclerView.ViewHolder,
                            pos: Int
                        ) {
                            viewHolder.itemView.scaleX = 0.9f
                            viewHolder.itemView.scaleY = 0.9f
                        }
                    })
            }

            categoryAll.apply {
                isNestedScrollingEnabled = false

                layoutManager = FlexboxLayoutManager(
                    context,
                    FlexDirection.ROW,
                    FlexWrap.WRAP
                ).apply {
                    justifyContent = JustifyContent.FLEX_START
                    alignItems = AlignItems.FLEX_START
                }

                addItemDecoration(
                    FlexboxItemDecoration(getIContext())
                        .apply {
                            setDrawable(getDrawableEx(R.drawable.rect_flex_space))
                        }
                )

                mAllAdapter = SlimAdapter.creator()
                    .register<PickCategory>(R.layout.item_pickup_category) { jector, bean, index ->
                        jector.apply {
                            text(R.id.item_category_name, bean.name)

                            getView<ImageView>(R.id.item_category_flag).apply {
                                isGone = bean.show
                                setImageResource(R.mipmap.icon_other01)
                            }

                            clicked(R.id.item_category_flag) {
                                categoryUpdate(
                                    arrayOf(
                                        "id" to bean.id,
                                        "show" to "1"
                                    )
                                ) {
                                    bean.show
                                        .conditionFalse {
                                            bean.show = true
                                            mAllAdapter.notifyItemChanged(index)
                                        }

                                    mCheckList.add(bean)
                                    mAdapter.notifyDataSetChanged()

                                    isModify = true
                                }
                            }
                        }
                    }
                    .attachTo(this)
            }
        }
    }

    override fun initListener() {
        mBinding.apply {
            categoryAdd.oneClick {
                showMemoDialog(
                    title = "添加分类",
                    hint = "请输入分类名称",
                    inputType = "text",
                    canEmpty = false
                ) { result ->
                    getViewModel()
                        .request(
                            requestUrl = BaseUrl.mngPickCateAdd,
                            isMultipart = true,
                            params = arrayOf(
                                "name" to result,
                                "type" to "dummy",
                                "orders" to "1000",
                            ),
                            onSuccess = { json ->
                                JsonUtil.jsonToBean(
                                    json,
                                    PickCategory::class.java
                                )?.let {
                                    mCheckList += it
                                    mAllList += it

                                    mAdapter.notifyDataSetChanged()
                                    mAllAdapter.notifyDataSetChanged()
                                }

                                isModify = true
                            }
                        )
                }
            }
        }
    }

    /**
     * 更新分类
     */
    private fun categoryUpdate(
        pair: Array<Pair<String, Any>>,
        onNext: (String) -> Unit
    ) {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngPickCateUpe,
                isMultipart = true,
                params = pair,
                onSuccess = onNext
            )
    }

    /**
     * 分类排序
     */
    private fun categorySort() {
        getViewModel()
            .request(
                requestUrl = BaseUrl.mngPickCateSrt,
                params = arrayOf(
                    "ids" to mCheckList.joinToString(",") { it.id }
                ),
                onSuccess = {
                    isModify = true

                    LogcatHelper.i("排序成功")
                }
            )
    }

    /**
     * 自提站点分类列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .categoryList(
                show = "",
                onSuccess = {
                    mAllList.apply {
                        clear()
                        addItems(it)
                    }

                    mCheckList.apply {
                        clear()
                        addItems(mAllList.filter { it.show })
                    }

                    mAdapter.setDataList(mCheckList)
                    mAllAdapter.setDataList(mAllList)
                }
            )
    }

    override fun onBackPressed() {
        isModify.condition {
            // 刷新站点分类
            LiveEventBus
                .get("pickCategory")
                .post("refresh")
        }

        super.onBackPressed()
    }

}